package com.example.demo5;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=findViewById(R.id.button_left);
        button.setOnClickListener(this);
        //动态添加碎片
        replaceFragment(new RightFragment());
    }

    private void replaceFragment(Fragment fragment) {
        //传递待添加的碎片实例
        //创建碎片容器
        FragmentManager fragmentManager = getSupportFragmentManager();
        //开始一个事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //替换容器里的碎片实例
        fragmentTransaction.replace(R.id.fragment,fragment);
        //添加返回栈达到返回上一操作的目的
        fragmentTransaction.addToBackStack(null);
        //提交事务
        fragmentTransaction.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //按钮的点击事件
            case R.id.button_left:
                replaceFragment(new AuthorRightFragment());
                break;
            default:
                break;
        }
    }

}
